{% extends "base_generic.html" %}
{% load i18n %}

{% block content %}

<div class="d-flex justify-content-between align-items-center">
    <h1>{{ book.title }}</h1>
    {% if user.is_authenticated %}
    <div class="d-flex align-items-center">
      <!-- Like Button -->
      <button id="like-btn" class="btn btn-outline-danger me-2" data-url="{% url 'toggle-like-book' book.pk %}">
        <i class="bi {% if user in book.likes.all %}bi-heart-fill{% else %}bi-heart{% endif %}"></i> 
        <span id="likes-count">{{ book.likes.count }}</span>
      </button>
      <!-- Favorite Button -->
      <button id="favorite-btn" class="btn btn-outline-warning" data-url="{% url 'toggle-favorite-book' book.pk %}">
        <i class="bi {% if user in book.favorites.all %}bi-star-fill{% else %}bi-star{% endif %}"></i> 
        <span id="favorites-count">{{ book.favorites.count }}</span>
      </button>
    </div>
    {% endif %}
  </div>

<p><strong>Author:</strong> <a href="{{ book.author.get_absolute_url }}">{{ book.author }}</a></p>
<p><strong>Summary:</strong> {{ book.summary }}</p>
<p><strong>ISBN:</strong> {{ book.isbn }}</p>
<p><strong>Language:</strong> {{ book.language }}</p>
<p><strong>Genre:</strong> {{ book.genre.all|join:", " }}</p>
<p><strong>Average Rating:</strong> {{ book.average_rating|floatformat:1 }} / 5.0 ({{ book.rating_count }} rating{{ book.rating_count|pluralize:"s" }})</p>

{% if user.is_authenticated and rating_form %}
  <hr>
  <h4>{% translate "Rate this book" %}</h4>
  <form action="{% url 'rate-book' book.pk %}" method="post" class="mt-3">
    {% csrf_token %}
    <div class="mb-3">
      <p><strong>{{ rating_form.rating.label }}:</strong></p>
      {% for radio in rating_form.rating %}
      <div class="form-check form-check-inline">
        {{ radio.tag }}
        <label class="form-check-label" for="{{ radio.id_for_label }}">{{ radio.choice_label }}</label>
      </div>
      {% endfor %}
      {% if rating_form.rating.errors %}
        <div class="invalid-feedback d-block">
          {% for error in rating_form.rating.errors %}
            <span>{{ error }}</span>
          {% endfor %}
        </div>
      {% endif %}
      {% if rating_form.rating.help_text %}
        <small class="form-text text-muted">{{ rating_form.rating.help_text|safe }}</small>
      {% endif %}
    </div>
    <button type="submit" class="btn btn-primary">{% translate "Submit Rating" %}</button>
  </form>
{% endif %}

<div style="margin-left:20px;margin-top:20px">
<h4>Copies</h4>

{% for copy in book.bookinstance_set.all %}
  <hr>
  <p class="{% if copy.status == 'a' %}text-success{% elif copy.status == 'd' %}text-danger{% else %}text-warning{% endif %}">{{ copy.get_status_display }}</p>
  {% if copy.status != 'a' %}<p><strong>Due to be returned:</strong> {{copy.due_back}}</p>{% endif %}
  <p><strong>Imprint:</strong> {{copy.imprint}}</p>
  <p class="text-muted"><strong>Id:</strong> <a href="{{ copy.get_absolute_url }}">{{copy.id}}</a></p>
{% empty %}
  <p>The library has no copies of this book.</p>
{% endfor %}
</div>

<hr>

<!-- Comments Section -->
<div class="mt-4">
  <h3>{% translate "Comments" %}</h3>

  {% if user.is_authenticated and comment_form %}
    <div class="card my-4">
      <div class="card-body">
        <h5 class="card-title">{% translate "Leave a comment" %}</h5>
        <form action="{% url 'add-comment-to-book' book.pk %}" method="post">
          {% csrf_token %}
          <div class="mb-3">
            {{ comment_form.text }}
            {% if comment_form.text.errors %}
              <div class="invalid-feedback d-block">
                {{ comment_form.text.errors }}
              </div>
            {% endif %}
          </div>
          <button type="submit" class="btn btn-success">{% translate "Submit Comment" %}</button>
        </form>
      </div>
    </div>
  {% else %}
    <p><a href="{% url 'login' %}?next={{ request.path }}">{% translate "Log in" %}</a> {% translate "to leave a comment." %}</p>
  {% endif %}

  {% for comment in book.comments.all %}
    <div class="card mb-3">
      <div class="card-body">
        <p class="card-text">{{ comment.text }}</p>
        <div class="text-muted small">
          -- {{ comment.user.username }} on {{ comment.created_at|date:"Y-m-d H:i" }}
        </div>
      </div>
    </div>
  {% empty %}
    <p>{% translate "No comments yet." %}</p>
  {% endfor %}
</div>

{% endblock %}

{% block javascript %}
<script>
  document.addEventListener('DOMContentLoaded', function() {
    const likeBtn = document.getElementById('like-btn');
    const favoriteBtn = document.getElementById('favorite-btn');
    const csrftoken = getCookie('csrftoken');

    if (likeBtn) {
      likeBtn.addEventListener('click', function() {
        toggleInteraction(this, 'likes-count', 'bi-heart', 'bi-heart-fill', 'liked');
      });
    }

    if (favoriteBtn) {
      favoriteBtn.addEventListener('click', function() {
        toggleInteraction(this, 'favorites-count', 'bi-star', 'bi-star-fill', 'favorited');
      });
    }

    function toggleInteraction(button, countElementId, emptyIcon, filledIcon, statusKey) {
      fetch(button.dataset.url, {
        method: 'POST',
        headers: {
          'X-CSRFToken': csrftoken,
          'Content-Type': 'application/json'
        }
      })
      .then(response => response.json())
      .then(data => {
        document.getElementById(countElementId).textContent = data[countElementId.replace('-', '_')];
        const icon = button.querySelector('i');
        if (data[statusKey]) {
          icon.classList.remove(emptyIcon);
          icon.classList.add(filledIcon);
        } else {
          icon.classList.remove(filledIcon);
          icon.classList.add(emptyIcon);
        }
      })
      .catch(error => console.error('Error:', error));
    }

    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
  });
</script>
{% endblock %}


{% block sidebar %}
  {{ block.super }}

  {% if perms.catalog.change_book or perms.catalog.delete_book %}
  <hr>
  <ul class="sidebar-nav">
    {% if perms.catalog.change_book %}
      <li><a href="{% url 'book-update' book.id %}">Update Book</a></li>
    {% endif %}
    {% if not book.bookinstance_set.all and perms.catalog.delete_book %}
      <li><a href="{% url 'book-delete' book.id %}">Delete Book</a></li>
    {% endif %}
    </ul>
  {% endif %}

{% endblock %}
